<template>
  <div>
    <!-- =========================== 主要表格区 ===================== -->
    <div class="main_table_area">
      <!-- 操作 -->
      <div class="op_btns">
        <el-button type="primary" @click="toSearch" class="el-icon-search" plain size="small">刷新表格</el-button>
        <el-button type="primary" @click="refreshAllSelections" class="el-icon-refresh" plain
          size="small">刷新下拉选项</el-button>
        <el-button type="danger" @click="batchDeleteByIds" class="el-icon-delete" plain size="small">批量删除选中角色</el-button>
        <el-button type="info" @click="batchDisableByIds" class="el-icon-turn-off" plain size="small">批量禁用选中角色</el-button>
        <el-button type="primary" @click="batchEnableByIds" class="el-icon-open" plain size="small">批量启用选中角色</el-button>
        <el-button type="primary" @click="showAddItemDrawer" class="el-icon-plus" plain size="small">新增角色</el-button>
      </div>
      <!-- 表格 -->
      <el-table :data="mainTable.data" border highlight-current-row size="small"
        @selection-change="selectionChangeHandle">
        <template slot="empty">
          <el-empty description="没有一个角色"></el-empty>
        </template>
        <!-- 复选列 -->
        <el-table-column type="selection" fixed></el-table-column>
        <!-- 序号列 -->
        <el-table-column type="index" label="序号"></el-table-column>
        <!-- 展开列 -->
        <el-table-column type="expand" label="详情">
          <template slot-scope="{row}">
            <el-descriptions :title="row.name" :column="1" border size="small">
              <el-descriptions-item :label="col.label" v-for="col in mainTable.expandColumns" :key="col.id">
                <span>{{ row[col.prop] }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </template>
        </el-table-column>
        <!-- 动态列 -->
        <el-table-column show-overflow-tooltip :min-width="col.minWidth" :label="col.label" :prop="col.prop"
          v-for="(col, index) in mainTable.columns" :key="index">
        </el-table-column>
        <!-- 特殊处理列 -->
        <el-table-column label="状态" min-width="30px">
          <template slot-scope="{row}">
            <el-tag type="success" v-if="row.enabled === 1">启用</el-tag>
            <el-tag type="info" v-else>禁用</el-tag>
          </template>
        </el-table-column>
        <!-- 操作列 -->
        <el-table-column label="操作" width="200px">
          <template slot-scope="{row}">
            <el-button type="primary" @click="showEditItemDrawer(row)" class="el-icon-edit" plain
              size="small">编辑</el-button>
            <el-tooltip :content="`给角色 ${row.name} 分配API`" placement="left-start">
              <el-button type="primary" @click="allocateInterface(row)" class="iconfont icon_api" plain
                size="small">API授权</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 主表分页 -->
      <div style="padding:10px; display: flex; justify-content:space-around; ">
        <el-pagination hide-on-single-page layout="total, sizes, prev, pager, next, jumper" next-text="下一页"
          prev-text="上一页" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="mainTable.page.currentPage" :page-size="mainTable.page.pageSize" :total="mainTable.page.total">
        </el-pagination>
      </div>
    </div>
    <!-- =========================== 新增角色抽屉 ==================== -->
    <div>
      <el-drawer :visible="addItemDrawer.visible" size="50%" direction="ltr" :before-close="addItemDrawerClose"
        title="新增角色">
        <div class="role_add_area">
          <div id="add_form">
            <el-form :model="addItemDrawer.data" ref="addItemFormRef" label-position="left" size="small">
              <el-form-item label="角色名" prop="name" label-width="100px">
                <el-input placeholder="请输入角色名" v-model="addItemDrawer.data.name" clearable></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="description" label-width="100px">
                <el-input type="textarea" placeholder="请输入描述信息" v-model="addItemDrawer.data.description"
                  clearable></el-input>
              </el-form-item>
              <el-form-item label="状态" label-width="100px" prop="enabled">
                <el-radio-group v-model="addItemDrawer.data.enabled" size="small">
                  <el-radio-button :label="s.value" v-for="s in select.statusWithLabel" :key="s.value">{{ s.label }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item label-width="100px">
                <el-button @click="addItemDrawer.visible = false">取消</el-button>
                <el-button @click="resetFieldsOfAddItemForm">重置</el-button>
                <el-button type="primary" @click="addItem">提交</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-drawer>
    </div>
    <!-- =========================== 编辑角色抽屉 ==================== -->
    <div>
      <el-drawer :visible="editItemDrawer.visible" size="50%" direction="ltr" :before-close="editItemDrawerClose"
        title="编辑角色">
        <div class="edit_role_area">
          <div id="edit_form">
            <el-form :model="editItemDrawer.data" ref="editItemFormRef" label-width="100px" label-position="left"
              size="small">
              <el-form-item label="角色名" prop="name">
                <el-input placeholder="请输入角色名" v-model="editItemDrawer.data.name" clearable></el-input>
              </el-form-item>
              <el-form-item label="角色描述" prop="description">
                <el-input type="textarea" placeholder="请输入描述信息" v-model="editItemDrawer.data.description"
                  clearable></el-input>
              </el-form-item>
              <el-form-item label="状态" prop="enabled">
                <el-radio-group v-model="editItemDrawer.data.enabled" size="small">
                  <el-radio-button :label="s.value" v-for="s in select.statusWithLabel" :key="s.value">{{ s.label }}
                  </el-radio-button>
                </el-radio-group>
              </el-form-item>
              <el-form-item>
                <el-button @click="editItemDrawer.visible = false">取消</el-button>
                <el-button type="primary" @click="editItem">提交</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </el-drawer>
    </div>
    <!-- =========================== API授权抽屉 ================== -->
    <div>
      <el-drawer :with-header="false" :visible="allocateApiDrawer.visible" size="100%" direction="btt"
        :before-close="allocateApiDrawerClose">
        <!-- 分配区 -->
        <div class="allocate_api_container">
          <!-- ======================= 已分配半区 ================== -->
          <div class="allocate_item" id="allocated_part">
            <h3>{{ allocateApiDrawer.role ? allocateApiDrawer.role.name : '' }} 已授权访问的接口</h3>
            <!-- 按钮 -->
            <div class="ops_btns">
              <el-button type="primary" @click="refreshAllApiSelections" class="el-icon-refresh" plain
                size="small">刷新下拉选项</el-button>
              <el-button type="primary" @click="pagingGetAllocatedApis" class="el-icon-refresh" plain
                size="small">刷新表格</el-button>
              <el-button type="danger" @click="batchDeleteApisOfRole" class="el-icon-delete" plain
                size="small">批量移除选中接口</el-button>
              <el-button type="info" @click="batchDisableApisOfRole" class="el-icon-turn-off" plain
                size="small">批量禁用选中接口</el-button>
              <el-button type="primary" @click="batchEnableApisOfRole" class="el-icon-open" plain
                size="small">批量启用选中接口</el-button>
              <a class="el-icon-caret-bottom" href="#unallocated_part">跳转到未分配部分</a>
              <el-button type="primary" @click="allocateApiDrawer.visible = false" class="el-icon-back" plain
                size="small">退出</el-button>
            </div>
            <!-- 选项区 -->
            <div class="select_area">
              <!-- 下拉选项一 -->
              <el-select @change="pagingGetAllocatedApis" v-model="allocateApiDrawer.allocated.searchData.apiGroup"
                placeholder="接口所属分组" size="small">
                <el-option label="所有分组" :value="null"></el-option>
                <el-option :label="g" :value="g" v-for="g in apiSelect.apiGroups" :key="g"></el-option>
              </el-select>
              <!-- 下拉选项二 -->
              <el-select @change="pagingGetAllocatedApis" v-model="allocateApiDrawer.allocated.searchData.className"
                placeholder="接口所属类" size="small">
                <el-option label="所有类" :value="null"></el-option>
                <el-option :label="c" :value="c" v-for="c in apiSelect.apiClassNames" :key="c"></el-option>
              </el-select>
              <!-- 下拉选项三 -->
              <el-select @change="pagingGetAllocatedApis" v-model="allocateApiDrawer.allocated.searchData.requestMethod"
                placeholder="请求方式" size="small">
                <el-option label="所有方式" :value="null"></el-option>
                <el-option :label="m" :value="m" v-for="m in apiSelect.apiRequestMethods" :key="m"></el-option>
              </el-select>
              <!-- 下拉选项四 -->
              <el-select @change="pagingGetAllocatedApis" v-model="allocateApiDrawer.allocated.searchData.enabled"
                placeholder="接口状态" size="small">
                <el-option label="所有状态" :value="null"></el-option>
                <el-option :label="s.label" :value="s.value" v-for="s in apiSelect.apiStatusesWithLabel"
                  :key="s.value"></el-option>
              </el-select>
            </div>
            <!-- 表格 -->
            <el-table :data="allocateApiDrawer.allocated.data" size="mini"
              @selection-change="allocatedTableSelectionChangeHandle">
              <template slot="empty">
                <el-empty :description="`${allocateApiDrawer.role.name} 角色还未被授权访问任何接口`"></el-empty>
              </template>
              <!-- 复选列 -->
              <el-table-column type="selection"></el-table-column>
              <!-- 动态列 -->
              <el-table-column :label="col.label" :prop="col.prop" :min-width="col.minWidth"
                v-for="col in allocateApiDrawer.allocated.columns" :key="col.id" show-overflow-tooltip>
              </el-table-column>
              <!-- 特殊处理列 -->
              <el-table-column label="api状态" min-width="30px">
                <template slot-scope="{row}">
                  <el-tag type="success" v-if="row.apiStatus === 1">启用</el-tag>
                  <el-tag type="info" v-else>禁用</el-tag>
                </template>
              </el-table-column>
              <el-table-column label="状态" min-width="30px">
                <template slot-scope="{row}">
                  <el-tag type="success" v-if="row.enabled === 1">启用</el-tag>
                  <el-tag type="info" v-else>禁用</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <div style="padding:10px; display: flex; justify-content:space-around; ">
              <el-pagination layout="total, sizes, prev, pager, next, jumper" @size-change="allocatedPageSizeChange"
                @current-change="allocatedPageNumChange" :current-page="allocateApiDrawer.allocated.page.currentPage"
                :page-size="allocateApiDrawer.allocated.page.pageSize" :total="allocateApiDrawer.allocated.page.total">
              </el-pagination>
            </div>
          </div>
          <!-- ====================== 未分配半区 ================== -->
          <div class="allocate_item" id="unallocated_part">
            <h3>{{ allocateApiDrawer.role ? allocateApiDrawer.role.name : '' }} 未授权访问的接口</h3>
            <!-- 操作 -->
            <div class="ops_btns">
              <el-button type="primary" @click="refreshAllApiSelections" class="el-icon-refresh" plain
                size="small">刷新下拉选项</el-button>
              <el-button type="primary" @click="pagingGetUnallocatedApis" class="el-icon-refresh" plain
                size="small">刷新表格</el-button>
              <el-button type="success" @click="batchAllocateApis" class="el-icon-open" plain
                size="small">批量分配选中接口</el-button>
              <a class="el-icon-caret-top" href="#allocated_part">跳转到已分配部分</a>
              <el-button type="primary" @click="allocateApiDrawer.visible = false" class="el-icon-back" plain
                size="small">退出</el-button>
            </div>
            <!-- 选项区 -->
            <div class="select_area">
              <!-- 下拉选项一 -->
              <el-select @change="pagingGetUnallocatedApis" v-model="allocateApiDrawer.unAllocated.searchData.apiGroup"
                placeholder="接口所属分组" size="small">
                <el-option label="所有分组" :value="null"></el-option>
                <el-option :label="g" :value="g" v-for="g in apiSelect.apiGroups" :key="g"></el-option>
              </el-select>
              <!-- 下拉选项二 -->
              <el-select @change="pagingGetUnallocatedApis" v-model="allocateApiDrawer.unAllocated.searchData.className"
                placeholder="接口所属类" size="small">
                <el-option label="所有类" :value="null"></el-option>
                <el-option :label="c" :value="c" v-for="c in apiSelect.apiClassNames" :key="c"></el-option>
              </el-select>
              <!-- 下拉选项三 -->
              <el-select @change="pagingGetUnallocatedApis"
                v-model="allocateApiDrawer.unAllocated.searchData.requestMethod" placeholder="请求方式" size="small">
                <el-option label="所有方式" :value="null"></el-option>
                <el-option :label="m" :value="m" v-for="m in apiSelect.apiRequestMethods" :key="m"></el-option>
              </el-select>
              <!-- 下拉选项四 -->
              <el-select @change="pagingGetUnallocatedApis" v-model="allocateApiDrawer.unAllocated.searchData.enabled"
                placeholder="接口状态" size="small">
                <el-option label="所有状态" :value="null"></el-option>
                <el-option :label="s.label" :value="s.value" v-for="s in apiSelect.apiStatusesWithLabel"
                  :key="s.value"></el-option>
              </el-select>
            </div>
            <!-- 表格 -->
            <el-table :data="allocateApiDrawer.unAllocated.data" size="mini"
              @selection-change="unAllocatedTableSelectionChangeHandle">
              <template slot="empty">
                <el-empty :description="`没有更多接口可在分配给角色 ${allocateApiDrawer.role.name}`"></el-empty>
              </template>
              <!-- 复选列 -->
              <el-table-column type="selection"></el-table-column>
              <!-- 动态列 -->
              <el-table-column :label="col.label" :prop="col.prop" :min-width="col.minWidth"
                v-for="col in allocateApiDrawer.unAllocated.columns" :key="col.id" show-overflow-tooltip>
              </el-table-column>
              <!-- 特殊处理列 -->
              <el-table-column label="api状态" min-width="40px">
                <template slot-scope="{row}">
                  <el-tag type="success" v-if="row.apiStatus === 1">启用</el-tag>
                  <el-tag type="info" v-else>禁用</el-tag>
                </template>
              </el-table-column>
            </el-table>
            <div style="padding:10px; display: flex; justify-content:space-around; ">
              <el-pagination layout="total, sizes, prev, pager, next, jumper" @size-change="unAllocatedPageSizeChange"
                @current-change="unAllocatedPageNumChange" :current-page="allocateApiDrawer.unAllocated.page.currentPage"
                :page-size="allocateApiDrawer.unAllocated.page.pageSize"
                :total="allocateApiDrawer.unAllocated.page.total">
              </el-pagination>
            </div>
          </div>
        </div>
      </el-drawer>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {

  data() {
    return {
      // ====================选项数据
      // 角色选项
      select: {
        statusWithLabel: [{ label: '禁用', value: 0 }],
      },
      // 接口选项：请求方式、状态、接口所属类、所属分组
      apiSelect: {
        apiRequestMethods: [],
        apiStatusesWithLabel: [],
        apiClassNames: [],
        apiGroups: [],
      },
      // ====================主要表格
      mainTable: {
        // 动态列
        columns: [
          {
            prop: 'name',
            label: '角色名称',
            minWidth: '80px',
          },
          {
            prop: 'description',
            label: '角色描述',
            minWidth: '200px',
          },
        ],
        // 展开列
        expandColumns: [
          {
            prop: 'id',
            label: 'ID',
          },
          {
            prop: 'name',
            label: '角色名称',
          },
          {
            prop: 'description',
            label: '角色描述',
          },
          {
            prop: 'creatorName',
            label: '创建者',
          },
          {
            prop: 'createAt',
            label: '创建时间',
          },
          {
            prop: 'updaterName',
            label: '更新者',
          },
          {
            prop: 'updateAt',
            label: '更新时间',
          },
        ],
        // 表格数据
        data: [],
        // 表格选中数据
        selectedData: [],
        // 分页数据
        page: {
          currentPage: 1,
          pageSize: 10,
          total: 0,
        },
        // 搜索
        search: {},
        // 添加
        addData: {},
        // 下拉选择
        enables: [],
      },
      // ====================新增角色
      addItemDrawer: {
        visible: false,
        // 绑定数据
        data: {
          id: -1,
          name: "",
          description: "",
          enabled: 0,
        },
      },
      // ====================编辑角色
      editItemDrawer: {
        visible: false,
        // 绑定数据
        data: {
          name: "",
          description: "",
          enabled: 0,
        },
      },
      // ====================API授权数据
      allocateApiDrawer: {
        // 抽屉可见性
        visible: false,
        // 分配接口需要操作的角色
        role: { id: -999, name: '不存在的接口' },
        // 已分配
        allocated: {
          // 表格选中数据
          selectedData: [],
          // 表格数据
          data: [],
          // 搜索数据
          searchData: {
            apiGroup: '',
            className: '',
            requestMethod: '',
            enabled: '',
          },
          // 分页
          page: {
            pageNum: 1,
            pageSize: 10,
            total: 0,
          },
          // 动态列
          columns: [
            {
              prop: 'id',
              label: 'ID',
              minWidth: '20px',
            },
            {
              prop: 'stableId',
              label: '稳定ID',
              minWidth: '30px',
            },
            {
              prop: 'requestPath',
              label: '路径',
              minWidth: '130px',
            },
            {
              prop: 'requestMethod',
              label: '方式',
              minWidth: '40px',
            },
            {
              prop: 'description',
              label: '描述',
              minWidth: '140px',
            },
            {
              prop: 'apiGroup',
              label: '分组',
              minWidth: '60px',
            },
            {
              prop: 'className',
              label: '所属类',
              minWidth: '100px',
            },
          ],
        },
        // 未分配
        unAllocated: {
          // 表格选中数据
          selectedData: [],
          // 表格数据
          data: [],
          // 搜索数据
          searchData: {
            apiGroup: '',
            className: '',
            requestMethod: '',
            enabled: '',
          },
          // 分页
          page: {
            pageNum: 1,
            pageSize: 10,
            total: 0,
          },
          // 动态列
          columns: [
            {
              prop: 'id',
              label: 'ID',
              minWidth: '20px',
            },
            {
              prop: 'stableId',
              label: '稳定ID',
              minWidth: '30px',
            },
            {
              prop: 'requestPath',
              label: '请求路径',
              minWidth: '130px',
            },
            {
              prop: 'requestMethod',
              label: '请求方式',
              minWidth: '50px',
            },
            {
              prop: 'description',
              label: '描述',
              minWidth: '140px',
            },
            {
              prop: 'apiGroup',
              label: '分组',
              minWidth: '60px',
            },
            {
              prop: 'className',
              label: '所属类',
              minWidth: '100px',
            },
          ],
        }
      },

    }
  },

  computed: {
    // 借助mapGetters生成计算属性：uiAuthValidateIsNotNeeded、roleAuths
    ...mapGetters('uiAuthModule', ['uiAuthValidateIsNotNeeded', 'roleAuths']),
    // 各个操作可用性计算属性
    addUserStatus() {
      const { addUser: { finalStatus } } = this.roleAuths
      return this.uiAuthValidateIsNotNeeded || finalStatus
    },
  },

  methods: {
    // #region 下拉选项方法开始
    // 刷新所有下拉选项
    refreshAllSelections() {
      this.refresAllStatus()
    },
    // 刷新状态选项
    async refresAllStatus() {
      const { data: res } = await this.$axios.get(`/admin/rolemanagement/allStatus`)
      if (res.code === 0) {
        this.$message.error(res.msg)
        return
      }
      this.select.statusWithLabel = res.data
    },

    // 刷新所有接口下拉选项数据
    refreshAllApiSelections() {
      this.refreshApiClassNames()
      this.refreshApiGroups()
      this.refreshApiRequestMethods()
      this.refreshApiStatuses()
    },
    // 刷新接口所属类
    async refreshApiClassNames() {
      const { data: res } = await this.$axios("/admin/interface/apiClassNames")
      if (res.code === 0) {
        this.$message.error(res.msg)
        return
      }
      this.apiSelect.apiClassNames = res.data
    },
    // 刷新接口分组
    async refreshApiGroups() {
      const { data: res } = await this.$axios("/admin/interface/apiGroups")
      if (res.code === 0) {
        this.$message.error(res.msg)
        return
      }
      this.apiSelect.apiGroups = res.data
    },
    // 刷新状态
    async refreshApiStatuses() {
      const { data: res } = await this.$axios("/admin/interface/apiStatuses")
      if (res.code === 0) {
        this.$message.error(res.msg)
        return
      }
      this.apiSelect.apiStatusesWithLabel = res.data
    },
    // 刷新请求方式
    async refreshApiRequestMethods() {
      const { data: res } = await this.$axios("/admin/interface/apiRequestMethods")
      if (res.code === 0) {
        this.$message.error(res.msg)
        return
      }
      this.apiSelect.apiRequestMethods = res.data
    },
    // #endregion 下拉选项结束

    // #region 主表操作方法开始
    // 表格复选
    selectionChangeHandle(selection) {
      this.mainTable.selectedData = selection
    },
    // 批量删除
    async batchDeleteByIds() {
      const ids = this.mainTable.selectedData.map(item => item.id)
      if (ids.length === 0) {
        this.$message.info("未选则要删除的角色")
      } else {
        try {
          await this.$confirm(`确定删除 ${ids.length} 个角色吗`)
          const { data: res } = await this.$axios({
            url: '/admin/rolemanagement/batchDeleteByIds',
            method: 'delete',
            data: ids
          })
          if (res.code === 0) {
            this.$message.error(res.msg)
            return
          }
          let msg = ""
          res.data.forEach(delInfo => {
            msg += `<p>${delInfo.label}: ${delInfo.delCount}</P>`
          })
          this.$notify({
            title: '删除详细',
            duration: 0,
            offset: 64,
            type: 'success',
            dangerouslyUseHTMLString: true,
            message: msg
          });
          this.mainTable.page.currentPage = 1
          this.pagingGettableData()
        } catch (e) {
          if (e === 'cancel') { return }
          this.$message.error(`删除失败`)
          console.dir(e)
        }
      }
    },
    // 批量启用
    batchEnableByIds() {
      const ids = this.mainTable.selectedData.map(item => item.id)
      if (ids.length === 0) {
        this.$message.info("未选则要启用的角色")
      } else {
        this.$axios({
          url: '/admin/rolemanagement/batchEnableRole',
          method: 'put',
          data: ids
        })
          .then((res) => {
            this.$message.success(`已启用 ${res.data.data} 个角色`)
            this.pagingGettableData()
          })
          .catch((err) => {
            this.$message.error(err.msg)
          })
      }
    },
    // 批量禁用
    batchDisableByIds() {
      const ids = this.mainTable.selectedData.map(item => item.id)
      if (ids.length === 0) {
        this.$message.info("未选则要禁用的角色")
      } else {
        this.$axios({
          url: '/admin/rolemanagement/batchDisableRole',
          method: 'put',
          data: ids
        })
          .then((res) => {
            this.$message.success(`已禁用用 ${res.data.data} 个角色`)
            this.pagingGettableData()
          })
          .catch((err) => {
            this.$message.error(err.msg)
          })
      }
    },
    // 搜索
    toSearch() {
      this.mainTable.page.currentPage = 1
      this.pagingGettableData()
    },
    // 分页获取表格数据
    async pagingGettableData() {
      try {
        const mainTable = this.mainTable
        const { data: res } = await this.$axios({
          url: `/admin/rolemanagement/pagingGetWithCondition/${mainTable.page.currentPage}/${mainTable.page.pageSize}`,
          method: 'post',
          data: this.mainTable.search,
        })
        if (res.code === 0) {
          this.$message.error(res.msg)
          return
        }
        mainTable.data = res.data.data
        mainTable.page.total = res.data.total
      } catch (error) {
        this.$message.error(`获取数据失败`)
        console.dir(error)
      }
    },
    // 分页组件处理
    handleSizeChange(pageSize) {
      this.mainTable.page.pageSize = pageSize
      this.pagingGettableData()
    },
    handleCurrentChange(currentPage) {
      this.mainTable.page.currentPage = currentPage
      this.pagingGettableData()
    },
    // #endregion 主表方法结束

    // #region 角色添加方法开始
    // 重置表单
    resetFieldsOfAddItemForm() {
      this.$refs.addItemFormRef.resetFields()
    },
    // 显示抽屉
    showAddItemDrawer() {
      this.addItemDrawer.visible = true
    },
    // 隐藏抽屉
    addItemDrawerClose(done) {
      this.addItemDrawer.visible = false
      this.pagingGettableData()
      done()
    },
    // 添加请求
    async addItem() {
      const { data: res } = await this.$axios({
        url: '/admin/rolemanagement/add',
        method: 'post',
        data: this.addItemDrawer.data,
      })
      if (res.code === 0) {
        this.$message.error(res.msg)
        return
      }
      this.$message.success(`已添加 ${res.data} 个角色`)
    },
    // #endregion 角色添加方法结束

    // #region 角色编辑方法开始
    // 显示抽屉
    showEditItemDrawer(role) {
      this.getRoleById(role)
      this.editItemDrawer.visible = true
    },
    // 获取待编辑角色
    async getRoleById(role) {
      const { data: res } = await this.$axios.get(`/admin/rolemanagement/${role.id}`)
      if (res.code === 0) {
        this.$message.error(res.msg)
        return
      }
      this.editItemDrawer.data = res.data
    },
    // 隐藏抽屉
    editItemDrawerClose(done) {
      this.editItemDrawer.visible = false
      this.pagingGettableData()
      done()
    },
    // 修改请求
    async editItem() {
      const { data: res } = await this.$axios({
        url: '/admin/rolemanagement/updateRoleById',
        method: 'put',
        data: this.editItemDrawer.data,
      })
      if (res.code === 0 && res.data > 0) {
        this.$message.error(res.msg)
        return
      }
      this.$message.success(res.msg)
    },
    // #endregion 角色编辑方法结束

    // #region 角色API授权方法开始
    // 展示抽屉
    allocateInterface(role) {
      const allocateApiDrawer = this.allocateApiDrawer
      allocateApiDrawer.role = role
      allocateApiDrawer.visible = true
      this.pagingGetAllocatedApis()
      this.pagingGetUnallocatedApis()
    },
    // 隐藏抽屉
    allocateApiDrawerClose(done) {
      this.allocateApiDrawer.visible = false
      done()
    },
    // ----------------------------------已分配接口表格
    // 删除角色的 一批接口
    async batchDeleteApisOfRole() {
      const apiStableIds = this.allocateApiDrawer.allocated.selectedData.map(item => item.stableId)
      if (apiStableIds.length === 0) {
        this.$message.warning('请选择要删除角色的哪些接口')
        return
      }
      try {
        const { data: res } = await this.$axios({
          url: `/admin/rolemanagement/batchDeleteApisOfRole/${this.allocateApiDrawer.role.id}`,
          method: 'delete',
          data: apiStableIds,
        })
        if (res.code === 0) {
          this.$message.error(res.msg)
          return
        }
        this.$message.success(`删除角色的 ${res.data} 条接口`)
        this.pagingGetAllocatedApis()
      } catch (error) {
        console.dir(error)
      }
    },
    // 分页获取角色已分配的接口
    async pagingGetAllocatedApis() {
      try {
        const aad = this.allocateApiDrawer
        const { data: res } = await this.$axios({
          url: `/admin/rolemanagement/getAllocatedApisOfRole/${aad.role.id}/${aad.allocated.page.pageNum}/${aad.allocated.page.pageSize}`,
          method: 'post',
          data: aad.allocated.searchData
        })
        if (res.code === 0) {
          this.$message.error(res.msg)
          return
        }
        aad.allocated.data = res.data.data
        aad.allocated.page.total = res.data.total
      } catch (e) {
        this.$message.error(e.msg)
        console.dir(e)
      }
    },
    // 禁用角色的一批接口
    async batchDisableApisOfRole() {
      const aad = this.allocateApiDrawer
      const apiStableIds = aad.allocated.selectedData.map(item => item.stableId)
      if (apiStableIds.length === 0) {
        this.$message.warning('请选择要禁用角色的哪些接口')
        return
      }
      const { data: res } = await this.$axios({
        url: `/admin/rolemanagement/batchDisableApisOfRole/${aad.role.id}`,
        method: 'put',
        data: apiStableIds,
      })
      if (res.code === 0) {
        this.$message.error(res.msg)
        return
      }
      this.$message.success(`已禁用角色的 ${res.data} 条接口`)
      this.pagingGetAllocatedApis()
    },
    // 启用角色的一批接口
    async batchEnableApisOfRole() {
      const aad = this.allocateApiDrawer
      const apiStableIds = aad.allocated.selectedData.map(item => item.stableId)
      if (apiStableIds.length === 0) {
        this.$message.warning('请选择要启用角色的哪些接口')
        return
      }
      const { data: res } = await this.$axios({
        url: `/admin/rolemanagement/batchEnableApisOfRole/${aad.role.id}`,
        method: 'put',
        data: apiStableIds,
      })
      if (res.code === 0) {
        this.$message.error(res.msg)
        return
      }
      this.$message.success(`已启用角色的 ${res.data} 条接口`)
      this.pagingGetAllocatedApis()
    },
    // 表格选中变化处理
    allocatedTableSelectionChangeHandle(selection) {
      this.allocateApiDrawer.allocated.selectedData = selection
    },
    // 分页变化处理
    allocatedPageSizeChange(pageSize) {
      this.allocateApiDrawer.allocated.page.pageSize = pageSize
      this.pagingGetAllocatedApis()
    },
    allocatedPageNumChange(pageNum) {
      this.allocateApiDrawer.allocated.page.pageNum = pageNum
      this.pagingGetAllocatedApis()
    },
    // -------------------------------------- 未分配接口表格
    // 批量分配接口给角色
    async batchAllocateApis() {
      const aad = this.allocateApiDrawer
      const apiStableIds = aad.unAllocated.selectedData.map(item => item.stableId)
      if (apiStableIds.length === 0) {
        this.$message.warning(`请选择要为角色 ${aad.role.name} 分配哪些接口`)
        return
      }
      try {
        const { data: res } = await this.$axios({
          url: `/admin/rolemanagement/batchAddApisToRole/${aad.role.id}`,
          method: 'post',
          data: apiStableIds,
        })
        if (res.code === 0) {
          this.$message.error(res.msg)
          return
        }
        this.$message.success(`已给角色 ${aad.role.name} 分配 ${res.data} 条接口`)
        this.pagingGetUnallocatedApis()
      } catch (error) {
        console.dir(error)
      }
    },
    // 获取角色未分配的接口
    async pagingGetUnallocatedApis() {
      const aad = this.allocateApiDrawer
      const { data: res } = await this.$axios({
        url: `/admin/rolemanagement/getUnallocatedApisOfRole/${aad.role.id}/${aad.unAllocated.page.pageNum}/${aad.unAllocated.page.pageSize}`,
        method: 'post',
        data: aad.unAllocated.searchData
      })
      if (res.code === 0) {
        this.$message.error(res.msg)
        return
      }
      aad.unAllocated.data = res.data == null ? null : res.data.data
      aad.unAllocated.page.total = res.data == null ? 0 : res.data.total
    },
    // 表格选中变化处理
    unAllocatedTableSelectionChangeHandle(selection) {
      this.allocateApiDrawer.unAllocated.selectedData = selection
    },
    // 分页变化处理
    unAllocatedPageSizeChange(pageSize) {
      this.allocateApiDrawer.unAllocated.page.pageSize = pageSize
      this.pagingGetUnallocatedApis()
    },
    unAllocatedPageNumChange(pageNum) {
      this.allocateApiDrawer.unAllocated.page.pageNum = pageNum
      this.pagingGetUnallocatedApis()
    },
    // #endregion 角色API授权结束
  },

  mounted() {
    this.pagingGettableData()
    this.refreshAllSelections()
    this.refreshAllApiSelections()
  }
}
</script>

<style lang="less" scoped>
.main_table_area {
  .op_btns {
    display: flex;
    justify-content: start;
    padding: 0 0 10px 0;
  }
}

.allocate_api_container {
  margin-left: 10px;

  .allocate_item {
    min-height: 600px;
    padding: 30px;
    box-shadow: 0px 0px 10px #000 inset;

    .el-table {
      height: 500px;
      overflow-y: auto;
    }
  }
}

#allocated_part,
#unallocated_part {
  margin-bottom: 50px;

  .ops_btns {
    display: flex;
    justify-content: flex-end;

    a {
      margin: 0 10px;
      background-color: #ecf5ff;
      color: #3a8ee6;
      display: block;
      text-decoration: none;
      box-sizing: border-box;
      border-radius: 5px;
      text-align: center;
      line-height: 30px;
      height: 30px;
      padding: 0 20px;
      box-shadow: 0 0 4px 0px #3a8ee6;
      font-size: 12px;
    }

    a:hover {
      color: #ecf5ff;
      background-color: #3a8ee6;
    }
  }

}

.role_add_area {
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-content: center;

  #add_form {
    width: 400px;
    border-radius: 10px;
    padding: 50px;
    box-shadow: 0 0 3px #000;
  }
}

.edit_role_area {
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-content: center;

  #edit_form {
    width: 400px;
    border-radius: 10px;
    padding: 50px;
    box-shadow: 0 0 3px #000;
  }
}

.select_area {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
}

.el-drawer__body {
  scroll-behavior: smooth;
}
</style>